import Fragment from './input/index.jsx';
import { h, render } from 'preact';
import OSS from 'ali-oss';

import './index.less';

var Input = function (oss, elem, opt) {
  return render(<Fragment {...opt} el={elem} oss={oss} obj={this} />, elem);
};

Input.prototype.getData = function () { }
Input.prototype.setData = function (v) { }
Input.prototype.addData = function (v) { }
Input.prototype.delData = function (i, s) { }


layui.define(['http', 'jquery', 'message'], function (exports) {
  exports('aliyun_oss', {
    ready: function (opt, callback, failure) {
      if (this.oss) return callback(this.oss);

      // 从网络加载OSS配置信息，并完成初始化
      layui.http.cache('/open/aliyun/oss.json', {
        bucket: this.bucket = (opt.bucket || 'ydd-rq'),
        region: this.region = (opt.region || 'oss-cn-chengdu'),
      }, (res) => callback(this.oss = new OSS(res.data)), failure);
    },
    upload: function (opt, fileName, file, success, failure) {
      this.ready(opt, (oss) => oss.multipartUpload(fileName, file, {
        progress: (percentage, checkpoint, res) => {
          console.log('上传进度:' + percentage * 100);
        }
      }).then(function (result) {
        if (success) success(result);
      }).catch(function (err) {
        if (failure) failure(err);
      }), failure);
    },
    render: function (elem, opt) {
      var el = $(elem);

      var entity = el.data('_entity');

      if (!entity || !entity.el || entity.el.nodeType != 1) {
        el.data('_entity', entity = new Input(this, el[0], opt));
      }

      return entity;
    }
  });
});


